# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
import random
import time
from selenium import webdriver
from scrapy.http import HtmlResponse
from time import sleep

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

class HouseSpiderSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class HouseSpiderDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)
# 延时爬取中间件
class RandomDelayMiddleware(object):
    def __init__(self, min_delay, max_delay):
        self.max_delay = max_delay
        self.min_delay = min_delay

    @classmethod
    def from_crawler(cls, crawler):

        max_delay = crawler.spider.settings.get("MAX_RANDOM_DELAY")
        min_delay = crawler.spider.settings.get("MIN_RANDOM_DELAY")
        if not isinstance(max_delay, int):
            raise ValueError("RANDOM_DELAY need a int")
        if not isinstance(min_delay, int):
            raise ValueError("RANDOM_DELAY need a int")
        return cls(min_delay, max_delay)

    def process_request(self, request, spider):
        # 爬取间隔 3~6s
        # request.headers.setdefault(b'User-Agent', UserAgent().random)
        delay = random.randint(self.min_delay, self.max_delay)
        # print("%s  get url %s" %((strftime("%Y-%m-%d %H:%M:%S", localtime())),request ))
        # print("### random delay: %s s ###" % delay)
        time.sleep(delay)

#添加selenium的支持，解决通过js动态加载数据的问题，解决办法是通过js执行滑动到底部
class SeleniumDownloaderMiddleware(object):

    def __init__(self):
        # 加载selenium信息
        firefox_opt = webdriver.FirefoxOptions()
        # 无浏览器模式加载
        firefox_opt.add_argument("--headless")
        self.driver = webdriver.Firefox(executable_path='../firefox_driver/geckodriver_28.exe',
                                        firefox_options=firefox_opt)

    def process_request(self, request, spider):
        self.driver.get(request.url)
        sleep(2)
        self.driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')  # js注入
        sleep(3)
        page_text = self.driver.page_source
        sleep(1)
        return HtmlResponse(url=request.url, body=page_text, encoding='utf-8', request=request)

class SeleniumRemoteDownloaderMiddleware(object):

    def __init__(self):
        # 加载selenium信息
        firefox_opt = webdriver.FirefoxOptions()
        # 无浏览器模式加载
        firefox_opt.add_argument("--headless")
        self.driver = webdriver.Remote(
            command_executor="http://192.168.1.25:4444/wd/hub",
            desired_capabilities=DesiredCapabilities.FIREFOX, )
        # self.driver = webdriver.Firefox(executable_path='../firefox_driver/geckodriver_28.exe',
        #                                 firefox_options=firefox_opt)

    def process_request(self, request, spider):
        self.driver.get(request.url)
        sleep(2)
        self.driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')  # js注入
        sleep(3)
        page_text = self.driver.page_source
        sleep(1)
        #self.driver.close()
        return HtmlResponse(url=request.url, body=page_text, encoding='utf-8', request=request)